#ifndef AUDIOPLAYER_H
#define AUDIOPLAYER_H

// 设置采样率
//format.setSampleRate(44100);
// 设置通道数
//format.setChannelCount(2);
// 设置样本大小
//format.setSampleSize(16);
// 设置编码格式
//format.setCodec("audio/pcm");
// 设置字节顺序
//format.setByteOrder(QAudioFormat::LittleEndian);
// 设置样本类型
//format.setSampleType(QAudioFormat::UnSignedInt);



#include "systemHead.h"
class AudioPlayer:public QObject
{
    Q_OBJECT
private:
    QAudioOutput *_audioOutput;
    QIODevice    *_device;
    int           _SampleRate = 48000;
    int           _Channels = 2;
    int           _SampleSize = 16;
    QString       _CodecFormat = "audio/pcm";
public:
    AudioPlayer(QObject *parent = nullptr)
        :QObject(parent)
    {

    }
    ~AudioPlayer()
    {
        if(_audioOutput != nullptr)
        {
            delete _audioOutput;
            _audioOutput = nullptr;
        }
    }
    void init()
    {
        QAudioFormat format;

        format.setSampleRate(_SampleRate);
        format.setChannelCount(_Channels);
        format.setSampleSize(_SampleSize);
        format.setCodec(_CodecFormat);
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::UnSignedInt);
        _audioOutput = new QAudioOutput(format);
        auto systemInfo = QAudioDeviceInfo::defaultOutputDevice();
        if(systemInfo.isFormatSupported(format))
        {
            _device = _audioOutput->start();
        }else{
            qDebug() << "system not support this format";
        }
        _audioOutput->setVolume(100);
    }

    void WriteData(const char *dataBuffer, int64_t size)
    {
        auto freeSpace = _audioOutput->bytesFree();
        while (size >= freeSpace) {
            //根据cpu的消耗，用这种方法（自旋锁），性价比不高
            freeSpace = _audioOutput->bytesFree();
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
        }

        _device->write(dataBuffer, size);
    }

};

#endif // AUDIOPLAYER_H
